/**
 * 
 */
package group.anglers.bpmn.core.service.impls;

import group.anglers.bpmn.core.local.models.ProcessContent;
import group.anglers.bpmn.core.local.services.ProcessArchived;
import group.anglers.bpmn.core.local.services.ProcessLocalService;
import group.anglers.om.core.exceptions.OmException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.EJB;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.ejb.Startup;

/**
 * @author an.pham
 * 
 */
@Singleton
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class ProcessArchivedImpl implements ProcessArchived {
	private Map<Long, String> archives = new HashMap<Long, String>();

	@EJB
	private ProcessLocalService processLocalService;

	@PostConstruct
	public void init() {
		try {
			List<ProcessContent> processContents = processLocalService.retrieveEnabled();

			if (processContents != null) {
				for (ProcessContent processContent : processContents) {
					put(processContent.getInstanceId(), processContent.getContent());
				}
			}
		} catch (OmException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	@Lock(LockType.WRITE)
	public void put(long instanceId, String content) {
		archives.put(instanceId, content);

	}

	@Override
	@Lock(LockType.READ)
	public String poll(long instanceId) {
		return archives.get(instanceId);
	}

}
